package com.zisuyi.uilibrary.uitils

import android.content.Context
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer
import android.media.SoundPool
import androidx.annotation.RawRes
import com.weilele.mvvm.app
import com.weilele.mvvm.utils.file.kvDecode
import com.weilele.mvvm.utils.file.kvEncode
import com.zisuyi.uilibrary.R
import kotlin.math.max

object SoundUtils {
    const val TYPE_SOUND_POOL = 1
    const val TYPE_MEDIA_PLAYER = 2

    enum class GameMusic(val bean: SoundBean) {
        //背景音乐
        Bg1(
            SoundBean(
                R.raw.bg_1,
                TYPE_MEDIA_PLAYER,
                false
            )
        ),
        Bg2(
            SoundBean(
                R.raw.bg_2,
                TYPE_MEDIA_PLAYER,
                false
            )
        ),
        Bg3(
            SoundBean(
                R.raw.bg_3,
                TYPE_MEDIA_PLAYER,
                false
            )
        ),
        Bg4(
            SoundBean(
                R.raw.bg_4,
                TYPE_MEDIA_PLAYER,
                false
            )
        ),
        Btn(
            SoundBean(
                R.raw.btn,
                TYPE_SOUND_POOL,
                false
            )
        ),
        HaQian(
            SoundBean(
                R.raw.haqian,
                TYPE_SOUND_POOL,
                false
            )
        ),
        DoubleCoin(
            SoundBean(
                R.raw.double_coin,
                TYPE_SOUND_POOL,
                false
            )
        ),
        Spin(
            SoundBean(
                R.raw.spin,
                TYPE_SOUND_POOL,
                true
            )
        ),
    }

    private val application = app
    private val soundPool by lazy {
        SoundPool.Builder()
            .setMaxStreams(10)
            .setAudioAttributes(
                AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build()
            )
            .build()
    }

    init {
        initSound(GameMusic.values().map { it.bean })
    }

    data class SoundBean(
        @RawRes var resId: Int,
        val type: Int,
        var isLoop: Boolean = false
    ) {
        internal var soundId: Int = 0
        internal var playId: Int = 0
        internal var mediaPlayer: MediaPlayer? = null
    }

    fun initSound(list: List<SoundBean>) {
        list.forEach {
            when (it.type) {
                TYPE_SOUND_POOL -> {
                    it.soundId = soundPool.load(application, it.resId, 1)
                }
                TYPE_MEDIA_PLAYER -> {
                    //背景音乐
                    createMediaPlayer(it)
                }
            }
        }
    }

    private fun createMediaPlayer(bean: SoundBean) {
        if (bean.mediaPlayer != null) {
            return
        }
        bean.mediaPlayer = MediaPlayer.create(application, bean.resId).apply {
            isLooping = bean.isLoop
        }
    }

    private val bgList = listOf(
        GameMusic.Bg1.bean,
        GameMusic.Bg2.bean,
        GameMusic.Bg3.bean,
        GameMusic.Bg4.bean,
    )


    var isCanPlayBg: Boolean
        set(value) {
            kvEncode("isCanPlayBg", value)
            if (value) {
                startPlayBg(bgList.random())
            } else {
                startPlayBg(null)
            }
        }
        get() = kvDecode("isCanPlayBg", true)

    fun autoCheckCanPlayBg() {
        if (isCanPlayBg) {
            startPlayBg(bgList.random())
        }
    }

    /**
     * 销魂的时候使用
     */
    fun stopBg() {
        bgList.toList().forEach {
            stop(it)
        }
    }

    private fun startPlayBg(bean: SoundBean?) {
        stopBg()
        bean?.mediaPlayer?.let {
            if (!it.isPlaying) {
                it.setOnCompletionListener { _ ->
                    it.setOnCompletionListener(null)
                    startPlayBg(bgList.random())
                }
                it.start()
            }
        }
    }

    /**
     * 播放
     */
    fun play(bean: SoundBean) {
        when (bean.type) {
            TYPE_SOUND_POOL -> {
                soundPool.autoPause()
                val volume = getVolume()
                bean.playId = soundPool.play(
                    bean.soundId, volume, volume, 1,
                    if (bean.isLoop) -1 else 0, 1.0f
                )
            }
            TYPE_MEDIA_PLAYER -> {
                bean.mediaPlayer?.let {
                    if (!it.isPlaying) {
                        it.start()
                    }
                }
            }
        }
    }

    /**
     * 停止
     */
    fun stop(bean: SoundBean) {
        when (bean.type) {
            TYPE_SOUND_POOL -> {
                soundPool.stop(bean.playId)
            }
            TYPE_MEDIA_PLAYER -> {
                bean.mediaPlayer?.let {
                    if (it.isPlaying) {
                        it.stop()
                        bean.mediaPlayer = null
                        createMediaPlayer(bean)
                    }
                }
            }
        }
    }

    /**
     * 暂停
     */
    fun pause(bean: SoundBean) {
        when (bean.type) {
            TYPE_SOUND_POOL -> {
                soundPool.pause(bean.playId)
            }
            TYPE_MEDIA_PLAYER -> {
                bean.mediaPlayer?.let {
                    if (it.isPlaying) {
                        it.pause()
                    }
                }
            }
        }
    }

    /**
     * 获取音量大小
     */
    private fun getVolume(): Float {
        val am = application.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        val audioMaxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC).toFloat()
        val volumeCurrent = am.getStreamVolume(AudioManager.STREAM_MUSIC).toFloat()
        return volumeCurrent / audioMaxVolume
    }
}